package com.iot.inter.controller.newinterface.multipleused;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.iot.inter.entity.newpojo.Constant;
import com.iot.inter.entity.newrequest.device.singledevicerealtime.request.RequestSingleDeviceRealTime;
import com.iot.inter.entity.newrequest.device.singledevicerealtime.response.ResponseSingleDeviceRealTime;
import com.iot.inter.entity.newrequest.device.singledevicerealtime.response.ResponseSingleDeviceRealTimeTradeData;
import com.iot.inter.entity.newrequest.device.singledevicerealtime.response.ResponseSingleDeviceRealTimeTradeDataPackageOrder;
import com.iot.inter.entity.newrequest.multipleused.request.RequestQueryToAheadFinished;
import com.iot.inter.entity.newrequest.multipleused.response.ResponseQueryToAheadFinished;
import com.iot.inter.entity.newrequest.packages.aheadfinish.request.RequestAheadFinishNew;
import com.iot.inter.entity.newrequest.packages.aheadfinish.response.ResponseAheadFinishNew;
import com.iot.inter.utils.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;

/**
 * 多接口同时使用：
 * <p>
 * 1,使用接口：3.3查询单一设备实时信息：查询出设备上是否有正在使用的订单；
 * <p>
 * 2,如果有直接发起 3.22	提前结束套餐订单： 提前结束掉正在使用的订单.
 *
 * @author lm
 * @date 2019/11/28
 */
@RestController
@Api(description = "查询正在使用并且提前结束掉正在使用的订单")

public class QueryToAheadFinishedController {

    private static Logger logger = Logger.getLogger(QueryToAheadFinishedController.class);

    @CrossOrigin
    @RequestMapping(value = "queryToAheadFinished", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询正在使用并且提前结束订单", response = ResponseQueryToAheadFinished.class)
    public String aheadFinishDeviceOrder(@ApiParam @RequestBody RequestQueryToAheadFinished request) {

        //3,定义要回复的内容
        String jsonString;
        String requestStr = JSON.toJSONString(request);
        ResponseQueryToAheadFinished response = new ResponseQueryToAheadFinished();

        if (null != requestStr) {

            logger.info("【查询并且提前结束订单】请求：" + requestStr);
            RequestQueryToAheadFinished requestPackage = JSONArray.parseObject(requestStr, RequestQueryToAheadFinished.class);
            String deviceCode = requestPackage.getDeviceCode();
            String deviceType = requestPackage.getDeviceType();
            String orderId = requestPackage.getOrderId();
            String aheadFinishCause = requestPackage.getAheadFinishCause();
            String secret = requestPackage.getSecret();
            String partnerCode = requestPackage.getPartnerCode();

            //1,现在去查询卡片上正在使用的订单操作
            RequestSingleDeviceRealTime deviceInfo = new RequestSingleDeviceRealTime();
            deviceInfo.setDeviceId(deviceCode);
            deviceInfo.setPartnerCode(partnerCode);
            deviceInfo.setSecret(secret);
            //组装需要的json去请求报文
            String requestInterface = JSON.toJSONString(deviceInfo);
            logger.info("【查询设备正在使用订单】请求：" + requestInterface);
            String url = "http://localhost:8085/iot/singleDeviceRealTime";
            // 发送post请求，并接收返回结果
            String returnStr = HttpUtil.httpPost(url, requestInterface);
            logger.info("【查询设备正在使用订单】响应：" + returnStr);
            ResponseSingleDeviceRealTime res = JSONArray.parseObject(returnStr, ResponseSingleDeviceRealTime.class);

            if (null != res && true == Constant.RET_CODE_0000.equalsIgnoreCase(res.getRetCode()) && null != res.getTradeData() && res.getTradeData().size() > 0) {

                for (ResponseSingleDeviceRealTimeTradeData tr : res.getTradeData()) {

                    if (null != tr.getPackageOrder() && tr.getPackageOrder().size() > 0) {

                        for (ResponseSingleDeviceRealTimeTradeDataPackageOrder pOrder : tr.getPackageOrder()) {

                            if (null != pOrder.getOrderCode() && !orderId.equalsIgnoreCase(pOrder.getOrderCode())) {

                                //2，现在去执行提前结束正在使用的订单操作
                                RequestAheadFinishNew aheadFinish = new RequestAheadFinishNew();
                                aheadFinish.setOrderId(pOrder.getOrderCode());
                                aheadFinish.setDeviceType(deviceType);
                                aheadFinish.setAheadFinishCause(aheadFinishCause);
                                aheadFinish.setPartnerCode(partnerCode);
                                aheadFinish.setSecret(secret);

                                String req = JSON.toJSONString(aheadFinish);
                                logger.info("【提前结束订单】请求：" + req);
                                String url1 = "http://localhost:8085/iot/aheadFinishDeviceOrderNew";
                                // 发送post请求，并接收返回结果
                                String returns = HttpUtil.httpPost(url1, req);
                                logger.info("【提前结束订单】响应：" + returns);
                                ResponseAheadFinishNew ress = JSONArray.parseObject(returns, ResponseAheadFinishNew.class);

                                if (null != ress && true == Constant.RET_CODE_0000.equalsIgnoreCase(ress.getRetCode()) && true == Constant.RET_CODE_0000.equalsIgnoreCase(ress.getError())) {

                                    //提前结束成功
                                    response.setRetCode(ress.getRetCode());
                                    response.setResultInfo(ress.getResultInfo());
                                    response.setError(ress.getError());
                                    response.setErrorMsg(ress.getErrorMsg());

                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(response);
                                    logger.info("【查询并且提前结束订单】成功响应：" + jsonString);
                                    return jsonString;
                                }

                            }

                        }

                    }

                }

            }

        }

        //除了提前结束成功其他情况都回复9998
        response.setRetCode("9998");
        response.setResultInfo("【提前结束订单】失败！");
        // 返回给调用者的报文
        jsonString = JSON.toJSONString(response);
        logger.info("【查询并且提前结束订单】失败响应：" + jsonString);
        return jsonString;
    }
}
